package demo3;

public class MySingleList {

    class ListNode {//内部类
        public int val;
        public ListNode Next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;

    public void createList() {
        ListNode node1 = new ListNode(12);
        ListNode node2 = new ListNode(23);
        ListNode node3 = new ListNode(34);
        ListNode node4 = new ListNode(45);
        ListNode node5 = new ListNode(56);
        node1.Next = node2;
        node2.Next = node3;
        node3.Next = node4;
        node4.Next = node5;
        this.head = node1;
    }

    public void show() {//创建单链表
        ListNode cur = head;

        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.Next;
        }
        System.out.println();
    }

    //头插法
    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        node.Next = head;
        head = node;
    }

    //尾插法
    public void addLast(int data) {
        ListNode node7 = new ListNode(data);
        ListNode cur = head;
        if (head == null) {
            head = node7;
        }
        while (cur.Next != null) {
            cur = cur.Next;
        }
        cur.Next = node7;
    }

    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index, int data) {
        ListNode node8 = new ListNode(data);
        ListNode cur = head;
        //判断index 的合法性
        if (index < 0 || index > size()) {
            throw new IndexOutOfBounds("位置不合法！");
        }
        if (index == 0) {
            addFirst(data);
            return;
        }
        if (index == size()) {
            addLast(data);
            return;
        }
        for (int i = 0; i < index; i++) {
            cur = cur.Next;
        }
        node8.Next = cur.Next;
        cur.Next = node8;
    }

    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key) {
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == key) {
                return true;
            }
            cur = cur.Next;
        }
        return false;
    }

    //删除第一次出现关键字为key的节点
    public void remove(int key) {
    }

    //删除所有值为key的节点
    public void removeAllKey(int key) {
    }

    //得到单链表的长度
    public int size() {
        int count = 0;
        ListNode cur = head;
        while (cur != null) {
            count++;
            cur = cur.Next;

        }
        return count;
    }

    public void clear() {
        //this.head = null;
        while (head != null) {
            ListNode headNext = head.Next;
            head = null;
            head = headNext;
        }
    }
}